import json
from django.conf import settings
import urllib.parse
from urllib.request import urlopen
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q
from apps.user.models import User


def jwt_response_payload_handler(token, user=None, request=None):
    """
    自定义jwt认证成功返回数据
    """
    return {
        'token': token,
        'id':user.id,
        'mobile': user.mobile,
        'username': user.username,
        'avatar':user.avatar
    }


def get_user_by_account(account):
    """根据帐号获取用户对象"""
    users = User.objects.filter(Q(username=account)|Q(mobile=account))
    if not users:
        return None
    return users[0]


class UsernameMobileAuthBackend(ModelBackend):
    """
    自定义用户名或手机号认证
    """
    def authenticate(self, request, username=None, password=None, **kwargs):
        """username可能是用户名， 也可能是手机号"""
        # 获取用户对象
        user = get_user_by_account(username)

        if user is not None and user.check_password(password):
            return user